import React from 'react';
import { message } from 'antd';
import moment from 'moment';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import { mapConfig } from 'Constants/mapConstants';
import { MAP_BUSINESS_TYPE_ICONS, MAP_ALERT_LEVEL } from 'Constants/AlertTableFilter';
import * as routerActions from 'react-router-redux';
import Business from './Business';
import Organize from './Organize';
import './index.scss';

const tabs = [
  {
    key: 1,
    label: '企业'
  },
  {
    key: 2,
    label: '监管机构'
  },
];
class Map extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 18, //地图级别,
      selectTab: 1,
      selectData: [],
      organiseData: [], //机构树数据
      businessAreaData: [], //企业区域数据
      mapBusinessData: [], //企业地图数据
      searchBusinessData: [], //搜索企业数据
      mapOrganiseData: [], //机构地图数据
      searchOrganiseData: [], //搜索机构数据
    };
    this.onLoad = ::this.onLoad;
    this.getOrganize = ::this.getOrganize;
    this.getBusinessArea = ::this.getBusinessArea;
    this.removeCenter = ::this.removeCenter;
    this.getBusinessDetail = ::this.getBusinessDetail;
    this.handleReloadOrganise = ::this.handleReloadOrganise;
    this.handleReloadBusiness = ::this.handleReloadBusiness;
  }
  componentDidMount() {
    //经纬度地图显示；
    this.map = new T.Map('mapContent');
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //先清除地图覆盖物，在显示
    // this.map.clearOverLays();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), this.state.zoom);
    this.getOrganize();
    this.getBusinessArea();
  }
  getIconUrl(data) {
    const selectedBusinessType = MAP_BUSINESS_TYPE_ICONS.filter(item => item.label === data.category)[0];
    let url = '';
    const alertLevel = parseInt(data.level, 10);
    if (alertLevel === parseInt(MAP_ALERT_LEVEL[0].key, 10)) {
      url = selectedBusinessType.alert_level1;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[1].key, 10)) {
      url = selectedBusinessType.alert_level2;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[2].key, 10)) {
      url = selectedBusinessType.alert_level3;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[3].key, 10)) {
      url = selectedBusinessType.alert_normal;
    }
    return url;
  }
  getOrganize() {
    const api = new Api({
      method: 'GET',
      path: '/depts',
      success: (json) => {
        this.setState({
          organiseData: json,
          mapOrganiseData: [],
        });
      },
    });
    api.run();
  }
  getBusinessArea() {
    const api = new Api({
      method: 'GET',
      path: '/justices/dept',
      success: (res) => {
        this.setState({
          businessAreaData: res
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  componentWillReceiveProps() {
    this.map.checkResize();
  }
  getBusinessDetail(data) {
    const self = this;
    const api = new Api({
      method: 'GET',
      path: `/enterprise_details/enterprise_info/${data.id}`,
      success: (res) => {
        console.log('res', res);
        this.map.clearOverLays();
        self.onLoad(this.state.searchBusinessData);
        this.infoWin = new T.InfoWindow();
        const lnglat = new T.LngLat(data.longitude, data.latitude);
        this.map.panTo(new T.LngLat(data.longitude, data.latitude), this.map.getZoom());
        this.infoWin.setLngLat(lnglat);
        this.infoWin.setOffset([-80, 100]);
        const cameraImg = res.sun_kitchens.length > 0 ? '<img src="./images/icon_video.png" id="map-video" />' : '';
        this.infoContent = `<div class="info-window-wrap">
            <div class="content">
              <div class="title">
                <div><img src="images/icon_hotel.png" alt="酒店"></div>
                <div>${res.name}</div>
              </div>
              <div class="item"><span>类型:</span><span>${res.type}</span></div>
              <div class="item"><span>经营范围:</span><span>${res.scope}</span></div>
              <div class="item"><span>注册日期:</span><span>${moment(res.reg_date).format('YYYY-MM-DD hh:mm:ss')}</span></div>
              <div class="item"><span>地址:</span><span>${res.address}</span></div>
              <div class="item"><span>联系人:</span><span>${res.legal_entity}</span></div>
              <div class="item map-img">${cameraImg}</div>
            </div>
          </div>
        `;
        this.infoWin.setContent(this.infoContent);
        this.map.addOverLay(this.infoWin);
        if (cameraImg) {
          document.getElementById('map-video').onclick = (e) => {
            this.props.dispatch(routerActions.push(`/system/dispatch/dispatch/video/map/${res.id}`));
            e.stopPropagation();
          };
        }
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }

  onLoad(data) {
    const self = this;
    const { selectTab } = this.state;
    if (selectTab === 1) {
      const markArr = [];
      for (let i = 0; i < data.length; i++) {
        const icon1 = new T.Icon({
          iconUrl: self.getIconUrl(data[i]),
          iconSize: new T.Point(30, 30),
          iconAnchor: new T.Point(15, 30)
        });
        //向地图上添加自定义标注
        const marker1 = new T.Marker(new T.LngLat(data[i].longitude, data[i].latitude), { icon: icon1 });
        markArr.push(marker1);
        this.map.addOverLay(marker1);
        // icon click
        marker1.addEventListener('click', () => {
          console.log(data[i]);
          this.getBusinessDetail(data[i]);
          self.setState({
            selectData: data[i]
          });
        });
      }
      // const markers = new T.MarkerClusterer(this.map, { markers: markArr });
      // console.log(markers);
    }
    if (selectTab === 2) {
      for (let i = 0; i < data.length; i++) {
        const icon1 = new T.Icon({
          iconUrl: 'images/icon_addr.png',
          iconSize: new T.Point(30, 36),
          iconAnchor: new T.Point(15, 36)
        });
        //向地图上添加自定义标注
        const marker1 = new T.Marker(new T.LngLat(data[i].longitude, data[i].latitude), { icon: icon1 });
        this.map.addOverLay(marker1);
        // icon click
        marker1.addEventListener('click', () => {
          self.setState({
            selectData: data[i]
          });
          this.map.clearOverLays();
          self.onLoad(data);
          this.infoWin = new T.InfoWindow();
          const lnglat = new T.LngLat(data[i].longitude, data[i].latitude);
          this.map.panTo(new T.LngLat(data[i].longitude, data[i].latitude), this.map.getZoom());
          this.infoWin.setLngLat(lnglat);
          this.infoWin.setOffset([0, -50]);
          this.infoContent = `<div class="info-window-wrap">
                                <div class="content">
                                <div class="title">${data[i].name}</div>
                                <div class="item"><span>地址:</span><span>${data[i].address || ''}</span></div>
                                <div class="item"><span>联系电话:</span><span>${data[i].phone || ''}</span></div>
                                <div class="item"><span>领导:</span><span>${data[i].leader || ''}</span></div>
                                </div> 
                              </div>
                              `;
          this.infoWin.setContent(this.infoContent);
          this.map.addOverLay(this.infoWin);
        });
      }
    }
  }
  handleClick(key) {
    const { mapBusinessData, mapOrganiseData } = this.state;
    this.setState({
      selectTab: key,
      selectData: {}
    }, () => {
      if (this.state.selectTab === 1) {
        this.map.clearOverLays();
        if (mapBusinessData.length > 0) {
          this.removeCenter(mapBusinessData);
        }
        this.onLoad(mapBusinessData);
      }
      if (this.state.selectTab === 2) {
        this.map.clearOverLays();
        if (mapOrganiseData.length > 0) {
          this.removeCenter(mapOrganiseData);
        }
        this.onLoad(mapOrganiseData);
      }
    });
  }
  // 改变地图中心点
  removeCenter(orData) {
    if (orData.length === 0) {
      return;
    }
    const data = orData.map(item => new T.LngLat(item.longitude, item.latitude));
    const res = this.map.getViewport(data);
    this.map.panTo(new T.LngLat(res.center.lng, res.center.lat), this.state.zoom);
  }
  renderSide() {
    const { selectTab, zoom } = this.state;
    const self = this;
    if (selectTab === tabs[0].key) {
      return (
        <Business
          businessAreaData={this.state.businessAreaData}
          selectData={this.state.selectData}
          reload={this.handleReloadBusiness.bind(this)}
          mapCenter={(item) => {
            if (item) {
              self.map.panTo(new T.LngLat(item.longitude, item.latitude), zoom);
            } else {
              self.map.panTo(new T.LngLat(mapConfig.longitude, mapConfig.latitude), zoom);
            }
          }}
        />
      );
    }
    return (
      <Organize
        organiseData={this.state.organiseData}
        selectData={this.state.selectData}
        reload={this.handleReloadOrganise.bind(this)}
        initData={this.handleOrgInit.bind(this)}
      />
    );
  }
  handleOrgInit(organise) {
    this.map.clearOverLays();
    this.removeCenter(organise);
    this.onLoad(organise);
  }
  handleReloadBusiness(business, searchValue) {
    if (searchValue && business.length > 0) {
      /*当有搜索的时候，地图中心以搜索的数据取中心*/
      const data = business.map(item => new T.LngLat(item.longitude, item.latitude));
      const newData = this.map.getViewport(data);
      this.map.panTo(new T.LngLat(newData.center.lng, newData.center.lat), newData.zoom);
    }
    this.setState({
      searchBusinessData: business
    });
    this.map.clearOverLays();
    this.onLoad(business);
  }
  handleReloadOrganise(organise) {
    this.setState({
      searchOrganiseData: organise,
      selectData: organise,
    });
    this.map.clearOverLays();
    this.map.panTo(new T.LngLat(organise.longitude, organise.latitude), 16);
    const newData = [];
    newData.push(organise);
    this.onLoad(newData);
  }
  render() {
    const { selectTab } = this.state;
    return (
      <div className="shian-map-page">
        <div className="side-wrap">
          <div className="side-content">
            <div className="title">
              {
                tabs.map(tab => (
                  <span
                    key={tab.key}
                    className={selectTab === tab.key ? 'tab-select' : ''}
                    onClick={this.handleClick.bind(this, tab.key)}
                  >{tab.label}</span>
                ))
              }
            </div>
            <div className="menu-content">
              {
                this.renderSide()
              }
            </div>
          </div>
        </div>
        <div className="map"><div id="mapContent" /></div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.mapReducer
  };
}

export default connect(mapStateToProps)(Map);
